package xyz.ibenben.zhongdian.system.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
import xyz.ibenben.zhongdian.common.annotation.SystemControllerLog;
import xyz.ibenben.zhongdian.common.constants.Constants;
import xyz.ibenben.zhongdian.system.entity.HouseBooking;
import xyz.ibenben.zhongdian.system.entity.sys.SysUser;
import xyz.ibenben.zhongdian.system.form.HouseBookingForm;
import xyz.ibenben.zhongdian.system.service.HouseBookingService;
import xyz.ibenben.zhongdian.system.service.impl.RedisService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.List;

/**
 * 房屋预售控制类
 * 提供了一些基本的服务，如初始化、获取房屋预售列表等方法。
 * spring mvc思想 通过controller来调用service里的方法，
 * service里的方法再通过调用Dao来实现对数据的操作
 * 返回值统统是String类型的返回页面有统一的安排方便代码提取
 *
 * @author chenjian
 * @since 2017年9月27日上午10:57:28
 */
@Controller
@SessionAttributes("houseBookingForm")
@RequestMapping("/houseBooking")
public class HouseBookingController extends BaseController {
    /**
     * 实体名称
     */
    private static final String ENTITYNAME = "houseBooking";

    @Resource
    private HouseBookingService houseBookingService;
    @Resource
    private RedisService redisService;

    /**
     * 初始化
     *
     * @param map              参数
     * @param houseBookingForm 条件参数
     */
    @ModelAttribute
    public void init(Model map, @ModelAttribute HouseBookingForm houseBookingForm, HttpSession session) {
        map.addAttribute("provinceList", redisService.get("provinceList"));
        map.addAttribute("cityList", redisService.get("cityList"));
        map.addAttribute("regionList", redisService.get("regionList"));
        HouseBookingForm newHouseBookingForm = new HouseBookingForm();
        if (houseBookingForm != null) {
            newHouseBookingForm = houseBookingForm;
        }
        SysUser user = (SysUser) session.getAttribute(Constants.SESSION);
        if (user != null && user.getSysRole() != null) {
            newHouseBookingForm.setCompanyId(user.getSysRole().getCompanyId());
        }
        map.addAttribute(String.format(Constants.FORMNAME, ENTITYNAME), newHouseBookingForm);
    }

    /**
     * 获取房屋预售列表
     *
     * @param map              参数
     * @param houseBookingForm 条件参数
     * @return 页面
     */
    @RequestMapping(value = "/getAll")
    @SystemControllerLog(description = "获取房屋预售列表")
    public String getAll(Model map, @ModelAttribute HouseBookingForm houseBookingForm) {
        map.addAttribute(String.format(Constants.FORMNAME, ENTITYNAME), houseBookingForm);
        Page<HouseBooking> page = PageHelper.startPage(houseBookingForm.getPageIndex(), houseBookingForm.getPageSize());
        List<HouseBooking> list = houseBookingService.findAll(houseBookingForm);
        map.addAttribute(String.format(Constants.LISTENTITY, ENTITYNAME), list);
        map.addAttribute(Constants.PI, page.toPageInfo());
        return String.format(Constants.LISTPAGE, ENTITYNAME);
    }

    /**
     * 删除房屋预售记录
     *
     * @param id      主键
     * @param request 请求
     * @return 页面
     */
    @RequestMapping(value = "/delete")
    @SystemControllerLog(description = "删除房屋预售记录")
    public String delete(@RequestParam("id") Long id, HttpServletRequest request, SessionStatus status) {
        houseBookingService.delete(id, request);
        status.setComplete();
        return String.format(Constants.REDIRECT, ENTITYNAME);
    }

    /**
     * 删除房屋预售列表
     *
     * @param houseBookingForm 条件参数
     * @param request          请求
     * @return 页面
     */
    @RequestMapping("/deleteAll")
    @SystemControllerLog(description = "删除房屋预售列表")
    public String deleteAll(@ModelAttribute HouseBookingForm houseBookingForm,
                            HttpServletRequest request, SessionStatus status) {
        if (houseBookingForm.getSelectIds() != null) {
            String[] ids = houseBookingForm.getSelectIds().split(Constants.COMMA);
            for (String id : ids) {
                houseBookingService.delete(Long.parseLong(id), request);
            }
        }
        status.setComplete();
        return String.format(Constants.REDIRECT, ENTITYNAME);
    }

    /**
     * 打开房屋预售添加页面
     *
     * @param map 参数
     * @return 页面
     */
    @GetMapping("/add")
    @SystemControllerLog(description = "打开房屋预售添加页面")
    public String openAddPage(Model map) {
        map.addAttribute(ENTITYNAME, new HouseBooking());
        return String.format(Constants.ADDPAGE, ENTITYNAME);
    }

    /**
     * 保存房屋预售记录
     *
     * @param houseBooking  实体
     * @param bindingResult 校验
     * @param request       请求
     * @return 页面
     */
    @PostMapping("/add")
    @SystemControllerLog(description = "保存房屋预售记录")
    public String postAddMessage(@Valid @ModelAttribute(ENTITYNAME) HouseBooking houseBooking,
                                 BindingResult bindingResult, HttpServletRequest request, SessionStatus status) {
        if (StringUtils.isNotBlank(houseBooking.getName())) {
            List<HouseBooking> list = houseBookingService.findByName(houseBooking.getName());
            if (null != list && !list.isEmpty()) {
                bindingResult.rejectValue("name", "misFormat", "这个新楼盘名称已经存在了！请更改!");
                return String.format(Constants.ADDPAGE, ENTITYNAME);
            }
        }
        if (!bindingResult.hasErrors()) {
            houseBookingService.save(houseBooking, request);
            status.setComplete();
            return String.format(Constants.REDIRECT, ENTITYNAME);
        } else {
            return String.format(Constants.ADDPAGE, ENTITYNAME);
        }
    }

    /**
     * 打开房屋预售修改页面
     *
     * @param map 参数
     * @param id  主键
     * @return 页面
     */
    @GetMapping("/edit")
    @SystemControllerLog(description = "打开房屋预售修改页面")
    public String openEditPage(Model map, @RequestParam("id") Long id) {
        map.addAttribute(ENTITYNAME, houseBookingService.findOneWithImage(id));
        return String.format(Constants.EDITPAGE, ENTITYNAME);
    }

    /**
     * 更新房屋预售修改记录
     *
     * @param houseBooking  实体
     * @param bindingResult 校验
     * @param request       请求
     * @return 页面
     */
    @PostMapping("/edit")
    @SystemControllerLog(description = "更新房屋预售修改记录")
    public String postEditMessage(@Valid @ModelAttribute(ENTITYNAME) HouseBooking houseBooking,
                                  BindingResult bindingResult, HttpServletRequest request, SessionStatus status) {
        HouseBooking info = houseBookingService.selectByKey(houseBooking.getId());
        if (!info.getName().equals(houseBooking.getName())) {
            List<HouseBooking> list = houseBookingService.findByName(houseBooking.getName());
            if (null != list && !list.isEmpty()) {
                bindingResult.rejectValue("name", "misFormat", "这个新楼盘名称已经存在了！请更改!");
                return String.format(Constants.EDITPAGE, ENTITYNAME);
            }
        }
        if (!bindingResult.hasErrors()) {
            houseBookingService.updateNotNull(houseBooking, request);
            status.setComplete();
            return String.format(Constants.REDIRECT, ENTITYNAME);
        } else {
            return String.format(Constants.EDITPAGE, ENTITYNAME);
        }
    }

    /**
     * 浏览房屋预售记录
     *
     * @param map              参数
     * @param id               主键
     * @param houseBookingForm 条件参数
     * @return 页面
     */
    @GetMapping("/view")
    @SystemControllerLog(description = "浏览房屋预售记录")
    public String openViewPage(Model map, @RequestParam("id") Long id,
                               @ModelAttribute HouseBookingForm houseBookingForm) {
        HouseBooking book = houseBookingService.findOneWithImage(id);
        if (null != book.getProvince()) {
            book.setProvinceName(redisService.get(book.getProvince().toString()).toString());
        }
        if (null != book.getCity()) {
            book.setCityName(redisService.get(book.getCity().toString()).toString());
        }
        if (null != book.getRegion()) {
            book.setRegionName(redisService.get(book.getRegion().toString()).toString());
        }
        map.addAttribute(ENTITYNAME, book);
        return String.format(Constants.VIEWPAGE, ENTITYNAME);
    }

}

